package com.ok.common.manager

import android.app.Activity
import android.content.Context
import kotlinx.coroutines.*
import java.util.*

class ActivityManager private constructor() : CoroutineScope by MainScope() {

    private var activities = LinkedList<Activity>()

    companion object {
        fun getInstance(): ActivityManager {
            return ActivityManagerHolder.holder
        }
    }

    private object ActivityManagerHolder {
        val holder = ActivityManager()
    }

    fun addActivity(activity: Activity) {
        launch(Dispatchers.IO) {
            withContext(Dispatchers.Main) {

            }
        }
        activities.add(activity)
    }

    fun removeActivity(activity: Activity?) {
        activities.remove(activity)
    }

    /**
     * 获取最顶层的Activity
     */
    fun getTopActivity(): Activity {
        return activities.last()
    }

    /**
     * 获取第一个Activity
     */
    fun getFirstActivity(): Activity {
        return activities.first
    }

    /**
     * 删除除最上层之外的所有activity
     */
    fun finishAllActivitiesExceptTop() {
        var topActivity = getTopActivity()
        var iterator = activities.iterator()
        while (iterator.hasNext()) {
            val activity = iterator.next()
            if (activity != topActivity) {
                activity.finish()
            }
        }
    }

    /**
     * 删除所有的activity
     */
    fun finishAllActivities() {
        val iterator = activities.iterator()
        while (iterator.hasNext()) {
            val activity = iterator.next()
            activity.finish()
            iterator.remove()
        }
    }

    fun finishAllActivities(clazz: Class<*>) {
        val iterator = activities.iterator()
        while (iterator.hasNext()) {
            val activity = iterator.next()
            if (activity.componentName.className != clazz.name) {
                activity.finish()
                iterator.remove()
            }
        }
    }


    /**
     * 判断当前Activity是否在前台
     */
    fun isForeground(context: Context, cls: Class<*>): Boolean {
        val manager = context.getSystemService(Context.ACTIVITY_SERVICE) as android.app.ActivityManager
        val list = manager.getRunningTasks(1)
        if (list != null && list.size > 0) {
            val topActivity = list[0].topActivity
            return topActivity!!.className == cls.name
        }
        return false
    }

}